package com.cqeec.waimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqeec.waimai.common.R;
import com.cqeec.waimai.dto.SetmealDto;
import com.cqeec.waimai.entity.Category;
import com.cqeec.waimai.service.CategoryService;
import com.cqeec.waimai.entity.Setmeal;
import com.cqeec.waimai.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    SetmealService setmealService;
    @Autowired
    CategoryService categoryService;
//    套餐管理页面分页查询
    @GetMapping("/page")
    public R<Page> getPage(int page,int pageSize,String name){
//        套餐分页查询
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Setmeal::getName,name);
        setmealService.page(pageInfo,wrapper);
//        扩展categoryName字段
        Page<SetmealDto> dtoPage = new Page<>(page,pageSize);
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<SetmealDto> list = pageInfo.getRecords().stream().map(item->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            Category category = categoryService.getById(item.getCategoryId());
            if (category!=null){
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }
//    新增套餐
    @PostMapping
    public R<String> addSetmeal(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }
//    删除、批量删除套餐
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids){
        setmealService.deleteById(ids);
        return R.success("删除成功");
    }
}
